package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.test.JacksonUtil;
import com.example.demo.vo.*;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.service.vod.model.request.VodSubmitDirectEditTaskAsyncRequest;
import com.volcengine.service.vod.model.response.VodSubmitDirectEditTaskAsyncResponse;
import org.springframework.web.bind.annotation.*;
import java.util.*;


@RestController
@RequestMapping("test")
public class TestController {

    final public static String endTime = "endTime";

    final public static String extraStart = "extraStart";

    final public static String startTime = "startTime";


    @PostMapping("/demo")
    public String demo(@RequestBody SignRequestVO signRequest){
        long time = new Date().getTime();
        System.out.println(time);
        //初始化
        IVodService vodService = VodServiceImpl.getInstance();
        //设置ak和sk
        vodService.setAccessKey("AKLTZmEyNzdjZDc0MGVkNDU4MGI5NDAyNjkzM2I0ZDVlNDU");
        vodService.setSecretKey("WVRnM01qRTFNRGxoWW1VM05ERmpOR0ZqWldOaVpESTVOR016TjJJell6Yw==");
        //转换json格式
        Map<String, Object> stringObjectMap = this.object2UpperCase(signRequest);
        System.out.println(JSONObject.toJSONString(stringObjectMap));
        //传值
        String paramsJsonString = JSON.toJSONString(stringObjectMap.get("EditParam"));
        String uploader = stringObjectMap.get("Uploader").toString();
        String application = stringObjectMap.get("Application").toString();
        VodSubmitDirectEditTaskAsyncRequest vodSubmitDirectEditTaskAsyncRequest = VodSubmitDirectEditTaskAsyncRequest.newBuilder()
                .setUploader(uploader)
                .setApplication(application)
                .setEditParam(ByteString.copyFromUtf8(paramsJsonString))
                .build();
        try {
            VodSubmitDirectEditTaskAsyncResponse vodSubmitDirectEditTaskAsyncResponse = vodService.submitDirectEditTaskAsync(vodSubmitDirectEditTaskAsyncRequest);
            if (vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().hasError()) {
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(vodSubmitDirectEditTaskAsyncResponse.toString()); // 编码采用UTF8
            System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getRequestId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = new Date().getTime();
        System.out.println("消耗时长="+(end-time) / 1000 /60);
        return "ok";

    }

    /**
     * 对象转json时属性变大写
     *
     * @param entity
     * @return
     */
    public Map<String,Object> object2UpperCase(Object entity){
        Map<String,Object> res = Maps.newHashMap();
        if (null==entity){
            return res;
        }
        //将对象的属性转化为大写
        String json = JacksonUtil.bean2Json(entity);
        Map<String,Object> map = JacksonUtil.json2Map(json,String.class,Object.class);
        if (null!=map && !map.isEmpty()){
            for(Map.Entry<String,Object> entry:map.entrySet()){
                /**
                 * TODO-关键在这里根据业务需要转大小写
                 */
                res.put(String.valueOf(entry.getKey().charAt(0)).toUpperCase()+entry.getKey().substring(1),entry.getValue());
            }
        }
        return res;
    }


    @PostMapping("/test")
    public String test(@RequestBody TestListVO testListVO){
      /*  IVodService vodService = VodServiceImpl.getInstance();
        //设置ak和sk
        vodService.setAccessKey("AKLTZmEyNzdjZDc0MGVkNDU4MGI5NDAyNjkzM2I0ZDVlNDU");
        vodService.setSecretKey("WVRnM01qRTFNRGxoWW1VM05ERmpOR0ZqWldOaVpESTVOR016TjJJell6Yw==");
        System.out.println(new Date().getTime());
        SignRequestVO signRequestVO = new SignRequestVO();
        EditParamVO editParamVO = this.editParam();
        signRequestVO.setEditParam(editParamVO);
        signRequestVO.getEditParam().getOutput().setFps(1);
        signRequestVO.getEditParam().getCanvas().setHeight(1);
        signRequestVO.getEditParam().getCanvas().setWidth(1);
        signRequestVO.getEditParam().getCodec().setVideoCodec("");*/

/*        signRequestVO.getEditParam().getUpload().setVideoName(submitVideoEditReq.getVideoName());
        signRequestVO.setCallbackUri(submitVideoEditReq.getCallbackUri());
        signRequestVO.setCallbackArgs(submitVideoEditReq.getCallbackArgs());
        signRequestVO.getEditParam().setTrack(lists);*/


        //初始化
        IVodService vodService = VodServiceImpl.getInstance();
        //设置ak和sk
        vodService.setAccessKey("AKLTZmEyNzdjZDc0MGVkNDU4MGI5NDAyNjkzM2I0ZDVlNDU");
        vodService.setSecretKey("WVRnM01qRTFNRGxoWW1VM05ERmpOR0ZqWldOaVpESTVOR016TjJJell6Yw==");
        System.out.println(new Date().getTime());
        SignRequestVO signRequestVO = new SignRequestVO();
        EditParamVO editParamVO = this.editParam();
        signRequestVO.setCallbackUri("https://dev.cloud.hokkj.cn/cloud/edata-video/generateCallback/generateVideoCallback");
        signRequestVO.setCallbackArgs("2312312312312321");
        signRequestVO.setEditParam(editParamVO);
        signRequestVO.getEditParam().getUpload().setVideoName(testListVO.getVideoName());
        signRequestVO.getEditParam().getOutput().getCodec().setCrf(testListVO.getMl());
        System.out.println(testListVO.getMl());
        int start = 0;
        int end = 0;
        Integer id = 1;
        List<List<TrackVO>> lists = new ArrayList<>();
        List<TrackVO> trackVOList = new ArrayList<>();
        for(TestVO testVO : testListVO.getList()){
            List<Integer> one = new ArrayList<>(2);
            ExtraVO extraOne = new ExtraVO();
            TrackVO trackVO = new TrackVO();
            trackVO.setID(testListVO.getVid());
            trackVO.setSource("vid://"+testListVO.getVid());
            List<ExtraVO> list = new ArrayList<>();
            extraOne.setStartTime(testVO.getStartTime());
            extraOne.setEndTime(testVO.getEndTime());
            end = start + (testVO.getEndTime()).intValue() - testVO.getStartTime().intValue();
            id = this.code(end, one, start, id, list, trackVO, trackVOList, extraOne);
            start = end;
        }
        lists.add(trackVOList);
        signRequestVO.getEditParam().setTrack(lists);

        Map<String, Object> stringObjectMap = this.object2UpperCase(signRequestVO);
        System.out.println(JSONObject.toJSONString(stringObjectMap));
        String paramsJsonString = JSON.toJSONString(stringObjectMap.get("EditParam"));
        String uploader = stringObjectMap.get("Uploader").toString();
        String application = stringObjectMap.get("Application").toString();
        VodSubmitDirectEditTaskAsyncRequest vodSubmitDirectEditTaskAsyncRequest = VodSubmitDirectEditTaskAsyncRequest.newBuilder()
                .setUploader(uploader)
                .setEditParam(ByteString.copyFromUtf8(paramsJsonString))
                .setApplication(application)
                .build();
            try {
                VodSubmitDirectEditTaskAsyncResponse vodSubmitDirectEditTaskAsyncResponse = vodService.submitDirectEditTaskAsync(vodSubmitDirectEditTaskAsyncRequest);
                if (vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().hasError()) {
                    System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getError());
                    System.exit(-1);
                }
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.toString()); // 编码采用UTF8
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getRequestId());
            } catch (Exception e) {
                e.printStackTrace();
            }      //初始化
        return "ok";

    }

    public EditParamVO editParam(){
        EditParamVO editParamVO = new EditParamVO();
        UploadVO uploadVO = new UploadVO();
        OutputVO outputVO = new OutputVO();
        CodecVO codecVO = new CodecVO();
        CanvasVO canvasVO = new CanvasVO();
        editParamVO.setOutput(outputVO);
        List<List<TrackVO>> lists = new ArrayList<>();
        List<TrackVO> list = new ArrayList<>();
        TrackVO trackVO = new TrackVO();
        list.add(trackVO);
        lists.add(list);
        editParamVO.setTrack(lists);
        editParamVO.setCanvas(canvasVO);
        editParamVO.setUpload(uploadVO);
        editParamVO.getOutput().setCodec(codecVO);
        return editParamVO;
    }


    @PostMapping("/time")
    public String time(@RequestBody TestListVO testListVO){

        //初始化
        IVodService vodService = VodServiceImpl.getInstance();
        //设置ak和sk
        vodService.setAccessKey("AKLTZmEyNzdjZDc0MGVkNDU4MGI5NDAyNjkzM2I0ZDVlNDU");
        vodService.setSecretKey("WVRnM01qRTFNRGxoWW1VM05ERmpOR0ZqWldOaVpESTVOR016TjJJell6Yw==");
        System.out.println(new Date().getTime());
        SignRequestVO signRequestVO = new SignRequestVO();
        EditParamVO editParamVO = this.editParam();
        signRequestVO.setEditParam(editParamVO);
        signRequestVO.getEditParam().getUpload().setVideoName(testListVO.getVideoName());
        Map<String , Long> endTimeMap = new HashMap<>();
        Map<String , Long> startTimeMap = new HashMap<>();
        Map<String , Long> extraStartMap = new HashMap<>();
        List<List<TrackVO>> lists = new ArrayList<>();
        List<TrackVO> trackVOList = new ArrayList<>();
        Integer start = 0;
        int end = 0;
        Integer id = 1;
        int size = 0;
        String str = null;
        for(TestVO testVO : testListVO.getList()) {
            size++;
            List<ExtraVO> extraVOS = new ArrayList<>();
            TrackVO trackVO = new TrackVO();
            trackVO.setID(testListVO.getVid());
            trackVO.setSource(testListVO.getSource());
            List<Integer> one = new ArrayList<>(2);
            if (Objects.nonNull(endTimeMap.get("endtime"))) {
                if (testVO.getStartTime().equals(endTimeMap.get("endtime"))) {
                    endTimeMap.clear();
                    endTimeMap.put("endtime", testVO.getEndTime());
                    if(size > testListVO.getList().size()){
                        ExtraVO extraOne = new ExtraVO();
                        end = start+(testVO.getEndTime().intValue() - testVO.getStartTime().intValue());
                        extraOne.setStartTime(testVO.getStartTime());
                        extraOne.setEndTime(testVO.getEndTime());
                        this.code(end,one,start,id,extraVOS,trackVO,trackVOList,extraOne);
                        str = JSONObject.toJSONString(testVO);
                        break;

                    }
                }else {
                    if(size > testListVO.getList().size()){
                        ExtraVO extraOne = new ExtraVO();
                        end = start+(testVO.getEndTime().intValue() - testVO.getStartTime().intValue());
                        extraOne.setStartTime(testVO.getStartTime());
                        extraOne.setEndTime(testVO.getEndTime());
                        id = this.code(end, one, start, id, extraVOS, trackVO, trackVOList, extraOne);
                        str = JSONObject.toJSONString(testVO);
                        break;
                    }
                    ExtraVO extraOne = new ExtraVO();
                    end = start+(endTimeMap.get("endtime").intValue() - startTimeMap.get("startTime").intValue());
                    extraOne.setStartTime(extraStartMap.get("extraStart"));
                    extraOne.setEndTime(endTimeMap.get("endtime"));
                    id = this.code(end, one, start, id, extraVOS, trackVO, trackVOList, extraOne);
                    start = end;
                    extraStartMap.put("extraStart", testVO.getStartTime());
                    endTimeMap.put("endtime", testVO.getEndTime());
                    startTimeMap.put("startTime", testVO.getStartTime());
                    str = JSONObject.toJSONString(testVO);
                }
            }else {
                extraStartMap.put("extraStart", testVO.getStartTime());
                startTimeMap.put("startTime", testVO.getStartTime());
                endTimeMap.put("endtime", testVO.getEndTime());
            }
        }


        TestVO testVO = JSONObject.toJavaObject(JSON.parseObject(str), TestVO.class);
        ExtraVO extraOne = new ExtraVO();
        end = start+(testVO.getEndTime().intValue() - testVO.getStartTime().intValue());
        extraOne.setStartTime(testVO.getStartTime());
        extraOne.setEndTime(testVO.getEndTime());
        List<Integer> one = new ArrayList<>(2);
        List<ExtraVO> extraVOS = new ArrayList<>();
        TrackVO trackVO = new TrackVO();
        trackVO.setID(testListVO.getVid());
        trackVO.setSource(testListVO.getSource());
        this.code(end, one, start, id, extraVOS, trackVO, trackVOList, extraOne);
        lists.add(trackVOList);
        signRequestVO.getEditParam().setTrack(lists);
        Map<String, Object> stringObjectMap = this.object2UpperCase(signRequestVO);
        String paramsJsonString = JSON.toJSONString(stringObjectMap.get("EditParam"));
        String uploader = stringObjectMap.get("Uploader").toString();
        String application = stringObjectMap.get("Application").toString();
        VodSubmitDirectEditTaskAsyncRequest vodSubmitDirectEditTaskAsyncRequest = VodSubmitDirectEditTaskAsyncRequest.newBuilder()
                .setUploader(uploader)
                .setApplication(application)
                .setEditParam(ByteString.copyFromUtf8(paramsJsonString))
                .build();
        try {
            VodSubmitDirectEditTaskAsyncResponse vodSubmitDirectEditTaskAsyncResponse = vodService.submitDirectEditTaskAsync(vodSubmitDirectEditTaskAsyncRequest);
            if (vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().hasError()) {
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getError());
                System.exit(-1);
            }
            System.out.println(vodSubmitDirectEditTaskAsyncResponse.toString()); // 编码采用UTF8
            System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getRequestId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(JSONObject.toJSONString(stringObjectMap));
        return "ok";
    }

/*    public void encapsulation(TestListVO testListVO,List<TrackVO> trackVOList ){
        Map<String , Long> endTimeMap = new HashMap<>();
        Map<String , Long> startTimeMap = new HashMap<>();
        Map<String , Long> extraStartMap = new HashMap<>();
        int start = 0;
        int end = 0;
        Integer id = 0;
        int size = 0;
        for(TestVO param : testListVO.getList()) {
            size++;
            List<ExtraVO> extraVOS = new ArrayList<>();
            TrackVO trackVO = new TrackVO();
            trackVO.setID(testListVO.getVid());
            trackVO.setSource(testListVO.getSource());
            List<Integer> one = new ArrayList<>(2);
            if (Objects.nonNull(endTimeMap.get(endTime))) {
                if (param.getStartTime().equals(endTimeMap.get(endTime))) {
                    endTimeMap.clear();
                    endTimeMap.put(endTime, param.getEndTime());
                    if(size >= testListVO.getList().size()){
                        ExtraVO extraOne = new ExtraVO();
                        end = start+(param.getEndTime().intValue() - param.getStartTime().intValue());
                        extraOne.setStartTime(param.getStartTime());
                        extraOne.setEndTime(param.getEndTime());
                        this.code(end,one,start,id,extraVOS,trackVO,trackVOList,extraOne);
                        break;
                    }
                }else {
                    if(size >= testListVO.getList().size()){
                        ExtraVO extraOne = new ExtraVO();
                        end = start+(param.getEndTime().intValue() - param.getStartTime().intValue());
                        extraOne.setStartTime(param.getStartTime());
                        extraOne.setEndTime(param.getEndTime());
                        this.code(end,one,start,id,extraVOS,trackVO,trackVOList,extraOne);
                        break;
                    }
                    ExtraVO extraOne = new ExtraVO();
                    end = start+(endTimeMap.get(endTime).intValue() - startTimeMap.get(startTime).intValue());
                    extraOne.setStartTime(extraStartMap.get(extraStart));
                    extraOne.setEndTime(endTimeMap.get(endTime));
                    id = this.code(end, one, start, id, extraVOS, trackVO, trackVOList, extraOne);
                    start = end;
                    extraStartMap.put(extraStart, param.getStartTime());
                    endTimeMap.put(endTime, param.getEndTime());
                    startTimeMap.put(startTime, param.getStartTime());
                }
            }else {
                extraStartMap.put(extraStart, param.getStartTime());
                startTimeMap.put(startTime, param.getStartTime());
                endTimeMap.put(endTime, param.getEndTime());
            }
        }
    }*/




    private Integer code(int end,List<Integer> one,int start,Integer id,List<ExtraVO> extraVOS,TrackVO trackVO,List<TrackVO> trackVOList,ExtraVO extraOne){
        ExtraVO extraTwo = new ExtraVO();
        one.add(start);
        one.add(end);
        extraOne.setID(id.toString());
        extraOne.setType("trim");
        extraVOS.add(extraOne);
        id = id+1;
        extraTwo.setID(id.toString());
        id = id+1;
        extraTwo.setType("transform");
        extraTwo.setHeight(1080);
        extraTwo.setWidth(1920);
        extraTwo.setPosX(0);
        extraTwo.setPosY(0);
        extraVOS.add(extraTwo);
        trackVO.setExtra(extraVOS);
        trackVO.setTargetTime(one);
        trackVOList.add(trackVO);
        return id;
    }





    @PostMapping("/exportProduct")
    public String exportProduct(@RequestBody ExportVideoListVo listVo){
        for(TestListVO testListVO : listVo.getList()) {
            //初始化
            IVodService vodService = VodServiceImpl.getInstance();
            //设置ak和sk
            vodService.setAccessKey("AKLTZmEyNzdjZDc0MGVkNDU4MGI5NDAyNjkzM2I0ZDVlNDU");
            vodService.setSecretKey("WVRnM01qRTFNRGxoWW1VM05ERmpOR0ZqWldOaVpESTVOR016TjJJell6Yw==");
            SignRequestVO signRequestVO = new SignRequestVO();
            EditParamVO editParamVO = this.editParam();
            signRequestVO.setEditParam(editParamVO);
            signRequestVO.getEditParam().getUpload().setVideoName(testListVO.getVideoName());
            List<List<TrackVO>> lists = new ArrayList<>();
            List<TrackVO> trackVOList = new ArrayList<>();
            Integer start = 0;
            int end = 0;
            Integer id = 1;
            for (TestVO testVO : testListVO.getList()) {
                List<ExtraVO> extraVOS = new ArrayList<>();
                TrackVO trackVO = new TrackVO();
                trackVO.setID(testListVO.getVid());
                trackVO.setSource(testListVO.getSource());
                List<Integer> one = new ArrayList<>(2);
                ExtraVO extraOne = new ExtraVO();
              /*  end = start + (testVO.getEnd_time()).intValue() - testVO.getStart_time().intValue();
                extraOne.setStartTime(testVO.getStart_time());
                extraOne.setEndTime(testVO.getEnd_time());*/
                id = this.code(end, one, start, id, extraVOS, trackVO, trackVOList, extraOne);
            }
            lists.add(trackVOList);
            signRequestVO.getEditParam().setTrack(lists);
            Map<String, Object> stringObjectMap = this.object2UpperCase(signRequestVO);
            String paramsJsonString = JSON.toJSONString(stringObjectMap.get("EditParam"));
            String uploader = stringObjectMap.get("Uploader").toString();
            String application = stringObjectMap.get("Application").toString();
            VodSubmitDirectEditTaskAsyncRequest vodSubmitDirectEditTaskAsyncRequest = VodSubmitDirectEditTaskAsyncRequest.newBuilder()
                    .setUploader(uploader)
                    .setApplication(application)
                    .setEditParam(ByteString.copyFromUtf8(paramsJsonString))
                    .build();
            try {
                VodSubmitDirectEditTaskAsyncResponse vodSubmitDirectEditTaskAsyncResponse = vodService.submitDirectEditTaskAsync(vodSubmitDirectEditTaskAsyncRequest);
                if (vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().hasError()) {
                    System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getError());
                    System.exit(-1);
                }
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.toString()); // 编码采用UTF8
                System.out.println(vodSubmitDirectEditTaskAsyncResponse.getResponseMetadata().getRequestId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(JSONObject.toJSONString(stringObjectMap));
        }
        return "ok";
    }

    @GetMapping("/getVideoListInfo")
    public List<VideoInfoVo> getVideoListInfo(Long projectId){
        List<VideoInfoVo> list = new ArrayList<>();
        return list;
    }

    @GetMapping("/getSubtitleInfo")
    public List<SubtitleInfoVo> getSubtitleInfo(Long projectId,String vid){
        List<SubtitleInfoVo> list = new ArrayList<>();
        return list;
    }

    @PostMapping("/export")
    public String export(@RequestBody ExportVideoVo exportVideoVo){
        return "ok";
    }

    @PostMapping("/updateStatus")
    public String updateStatus(Long id,String vid,Integer status){
        return "ok";
    }



    @PostMapping("/callback")
    public Boolean callback(String ReqId,String Vid){
        System.out.println(ReqId);
        return true;
    }




}
